package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author fanYuLe
 * @Date 2023/3/8 17:52
 * @Blog blog.fanYuLe.net/996.mba
 * @Description:
 */
@RestController
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    //分类列表
    @GetMapping("/category/list")
    public ResultInfo findAll(){
        List<Category> list = null;
        //先查询缓存
        String categoryKey ="category_list";
        if(redisTemplate.hasKey(categoryKey)){
             list = (List<Category>) redisTemplate.opsForValue().get(categoryKey);
             log.info("查询redis缓存");
        }else{
            //调用service查询mysql
            list = categoryService.findAll();
            log.info("查询MySQL数据库");
            //同步到redis中
            redisTemplate.opsForValue().set(categoryKey,list);
        }
        return ResultInfo.success(list);
    }
}

